package com.sbio.udiapp.ui;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.LogPrinter;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sbio.udiapp.R;
import com.sbio.udiapp.adapter.PackingListViewAdapter;
import com.sbio.udiapp.common.bean.PackVo;
import com.sbio.udiapp.common.bean.PrintVo;
import com.sbio.udiapp.cpcl.PrintUtil;
import com.sbio.udiapp.databinding.ActivityPackingBinding;
import com.sbio.udiapp.net.api.ApiService;
import com.sbio.udiapp.net.exception.ApiException;
import com.sbio.udiapp.net.exception.ErrorConsumerAdapter;
import com.sbio.udiapp.net.exception.ErrorConsumerAdapterBuilder;
import com.sbio.udiapp.net.response.ResponseTransformer;
import com.sbio.udiapp.util.CollectionUtils;
import com.sbio.udiapp.util.DefaultSharedPreferencesUtil;
import com.sbio.udiapp.util.DialogUtil;
import com.sbio.udiapp.util.IntentUtil;
import com.sbio.udiapp.util.JsonUtil;
import com.sbio.udiapp.util.LogTag;
import com.sbio.udiapp.util.LogUtil;
import com.sbio.udiapp.util.SharedPreferencesUtil;
import com.sbio.udiapp.util.SoundPlayerUtil;
import com.sbio.udiapp.util.StringUtil;
import com.sbio.udiapp.util.ToastUtil;
import com.sbio.udiapp.util.VibratorUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class PackingActivity extends BaseBroadCastActivity implements View.OnClickListener {

    private ActivityPackingBinding binding;

    private ObservableList<String> datas = new ObservableArrayList<>();

    private PackingListViewAdapter packingListViewAdapter;

    @Inject
    ApiService apiService;

    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPackingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
//        binding.boxCodeScan.requestFocus();
        //盒码扫描框绑定事件-回车添加数据
        /*binding.boxCodeScan.setOnEditorActionListener((v, actionId, event) -> {
            String text = binding.boxCodeScan.getText().toString();
            binding.boxCodeScan.setText("");
            if (TextUtils.isEmpty(text)) {
                VibratorUtil.vibrator();
                return true;
            }
            String maxCountStr = binding.etMaxCount.getText().toString();
            Integer maxCount = null;
            if (!TextUtils.isEmpty(maxCountStr)) {
                maxCount = Integer.valueOf(maxCountStr);
                if (datas.size() >= maxCount) {
                    binding.boxCodeScan.setText("");
                    DialogUtil.showCommonAlertDialog("已经达到最大数量，输入框已清空");
                    return true;
                }
            }
            if (datas.contains(text)) {
                binding.boxCodeScan.setText("");
                //弹出提示框
                DialogUtil.showCommonAlertDialog("数据重复，输入框已清空", () -> {
                    binding.boxCodeScan.setText("");
                    binding.boxCodeScan.requestFocus();
                });
                return true;
            }
//                apiService.hello("zhangsan");
            String data0 = "";
            if (DefaultSharedPreferencesUtil.useDeptIsProduct(this) && CollectionUtils.isNotEmpty(datas)) {
                data0 = datas.get(0);
                //如果前两个字不一样就说明，不是同一类型（箱码和udi码）
                if (!data0.substring(0, 2).equals(text.substring(0, 2))) {
                    ToastUtil.showError("不是同一类型的码");
                    return false;
                }
            }
            String useDept = DefaultSharedPreferencesUtil.getUseDept(this);

//            boolean isFocused = binding.boxCodeScan.isFocused();
            Integer finalMaxCount = maxCount;
            long l = System.currentTimeMillis();
            apiService.checkPackScanBoxCode(text, data0, useDept)
                    .compose(ResponseTransformer.obtain())
                    .subscribe(ajaxResult -> {
                        if (ajaxResult.getData(Boolean.class) && !datas.contains(text)) {
                            ToastUtil.showLong("添加成功");
                            String deviceNo = DefaultSharedPreferencesUtil.getDeviceNo(this);
                            LogUtil.file("装箱扫码", "扫码为：" + text);
                            datas.add(text);
                            binding.boxCodeScan.setText("");
                            packingListViewAdapter.notifyDataSetChanged();
                            Log.i("tag1111", "时间2:" + (System.currentTimeMillis() - l));
                            binding.boxCodeScan.postDelayed(() -> {
                                binding.boxCodeScan.requestFocus();
                            }, 100);
                            SoundPlayerUtil.playSuccess();
                            if (finalMaxCount != null && datas.size() == finalMaxCount) {
                                //达到最大震动一下
                                VibratorUtil.vibrator();
                            }
                            return;
                        }

                        binding.boxCodeScan.setText("");
                        //弹出提示框
                        DialogUtil.showCommonAlertDialog(ajaxResult.getMsg(), () -> binding.boxCodeScan.requestFocus());
                    }, ErrorConsumerAdapterBuilder.builder()
                            .before((ex) -> {
                                binding.boxCodeScan.setText("");
                                binding.boxCodeScan.requestFocus();
                            })
                            .build());
//            Log.i("tag1111", "时间1:" + (System.currentTimeMillis() - l));
            return false;


        });*/
        //设置listViewAdapter
        packingListViewAdapter = new PackingListViewAdapter(this, binding.boxCodeScan, datas);
        binding.lvBoxCode.setAdapter(packingListViewAdapter);

        //装箱按钮绑定事件
        binding.btnPacking.setOnClickListener(this);

        datas.addOnListChangedCallback(new ObservableList.OnListChangedCallback<ObservableList<String>>() {
            @Override
            public void onChanged(ObservableList<String> sender) {
                setTitle(getString(R.string.packing) + "(" + datas.size() + "个)");
            }

            @Override
            public void onItemRangeChanged(ObservableList<String> sender, int positionStart, int itemCount) {
                setTitle(getString(R.string.packing) + "(" + datas.size() + "个)");
            }

            @Override
            public void onItemRangeInserted(ObservableList<String> sender, int positionStart, int itemCount) {
                setTitle(getString(R.string.packing) + "(" + datas.size() + "个)");
            }

            @Override
            public void onItemRangeMoved(ObservableList<String> sender, int fromPosition, int toPosition, int itemCount) {
                setTitle(getString(R.string.packing) + "(" + datas.size() + "个)");
            }

            @Override
            public void onItemRangeRemoved(ObservableList<String> sender, int positionStart, int itemCount) {
                setTitle(getString(R.string.packing) + "(" + datas.size() + "个)");
            }
        });

//        listView1Adapter.notifyDataSetChanged();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 装箱按钮绑定事件
            case R.id.btn_packing: {
                Integer maxCount = null;
                String maxCountStr = binding.etMaxCount.getText().toString();
                if (!StringUtils.isEmpty(maxCountStr)) {
                    maxCount = Integer.valueOf(maxCountStr);
                }

                if (maxCount != null && datas.size() != maxCount) {
                    DialogUtil.showErrorAlertDialog("没有达到最大数量，不允许提交");
                    break;
                }
                PackVo pack = new PackVo();
                pack.setBoxCode(datas);
                pack.setPackStatus(PackVo.packed);
                apiService.packing(pack)
                        .compose(ResponseTransformer.obtain())
                        .subscribe(ajaxResult -> {
//                            ToastUtil.show("装箱成功");
                            Object data = ajaxResult.getData();
                            ObjectMapper objectMapper = new ObjectMapper();
                            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                            PrintVo printVo = objectMapper.convertValue(data, PrintVo.class);
                            String packNo = printVo.getPackNo();
                            DialogUtil.showCommonAlertDialog("装箱成功，箱码为：" + packNo);

//                            PrintVo printVo = new PrintVo();
//                            printVo.setLot("230704001");
//                            printVo.setSpec("48 Tests/Kit（8 tests/platex 6）");
//                            printVo.setMaterialName("Streptococcus pneumoniae,Legionella pneumophila and Haemophilus influenzae Real Time PCR Kit");
//                            printVo.setMaterialNo("C.02.01.008.0289（RUO）");
//                            printVo.setCount(datas.size());
//                            printVo.setPackNo(packCode);
                            SharedPreferencesUtil.saveString("printVo", JsonUtil.toJsonString(printVo));
                            PrintUtil.printQR(printVo);
                            //清空数据并刷新页面
                            datas.clear();
                            packingListViewAdapter.notifyDataSetChanged();
                            //返回主页
//                            Intent intent = new Intent(this, MainActivity.class);
//                            startActivity(intent);
                        }, new ErrorConsumerAdapter());

                break;
            }
            default:
                break;
        }
    }

    @Override
    public void onBroadcastReceiver(String barcodeData) {

        LogUtil.file("接收到广播数据", barcodeData);
        if (progressCount.get() > 0) {
            ToastUtil.showWait("请等待上一个结果返回");
            return;
        }
        if (datas.contains(barcodeData)) {
            ToastUtil.showError("数据重复");
            return;
        }
        //如果是出库申请开头的数据那么就是outStockApplyNos
        if (barcodeData.indexOf("XM") == 0 || barcodeData.indexOf("01") == 0) {
            String data0 = "";
            if (DefaultSharedPreferencesUtil.useDeptIsProduct(PackingActivity.this) && CollectionUtils.isNotEmpty(datas)) {
                data0 = datas.get(0);
                //如果前两个字不一样就说明，不是同一类型（箱码和udi码）
                if (!data0.substring(0, 2).equals(barcodeData.substring(0, 2))) {
                    ToastUtil.showError("不是同一类型的码");
                    return;
                }
            }
            String useDept = DefaultSharedPreferencesUtil.getUseDept(PackingActivity.this);
            Integer maxCount = null;
            String maxCountStr = binding.etMaxCount.getText().toString();
            if (!TextUtils.isEmpty(maxCountStr)) {
                maxCount = Integer.valueOf(maxCountStr);
                LogUtil.file("packing","最大数量:"+maxCount+"data size:"+datas.size());
                if (datas.size() >= maxCount) {
                    //                            binding.boxCodeScan.setText("");
                    DialogUtil.showCommonAlertDialog("已经达到最大数量"+maxCount+"，输入框已清空");
                    return;
                }
            }
            Integer finalMaxCount = maxCount;
            long l = System.currentTimeMillis();
            apiService.checkPackScanBoxCode(barcodeData, data0, useDept)
                    .compose(ResponseTransformer.obtain())
                    .subscribe(ajaxResult ->  {
                        if (ajaxResult.getData(Boolean.class) && !datas.contains(barcodeData)) {
                            ToastUtil.showLong("添加成功");
                            String deviceNo = DefaultSharedPreferencesUtil.getDeviceNo(PackingActivity.this);
                            LogUtil.file("装箱扫码", "扫码为：" + barcodeData);
                            datas.add(barcodeData);
                            //                                    binding.boxCodeScan.setText("");
                            packingListViewAdapter.notifyDataSetChanged();
                            Log.i("tag1111", "时间2:" + (System.currentTimeMillis() - l));
                            //                                    binding.boxCodeScan.postDelayed(() -> {
                            //                                        binding.boxCodeScan.requestFocus();
                            //                                    }, 100);
                            SoundPlayerUtil.playSuccess();
                            if (finalMaxCount != null && datas.size() == finalMaxCount) {
                                //达到最大震动一下
                                VibratorUtil.vibrator();
                            }
                            return;
                        }

                        //                                binding.boxCodeScan.setText("");
                        //弹出提示框
                        DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
                        //                                DialogUtil.showCommonAlertDialog(ajaxResult.getMsg(), () -> binding.boxCodeScan.requestFocus());
                    }, ErrorConsumerAdapterBuilder.builder()
                            .before((ex) -> {
                                //                                        binding.boxCodeScan.setText("");
                                //                                        binding.boxCodeScan.requestFocus();
                            })
                            .build());
        } else {
            //非法数据
            ToastUtil.showError("非法数据，请检查");
            return;
        }

    }


    /*public void initSystemScanData() {

        // 新建一个广播接收对象，实现数据接收和处理
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    if (action==null) {
                        return;
                    }
                    String data = IntentUtil.getStringExtra(intent);

                    switch (action) {
                        case IntentUtil.INTENT_ACTIONS_DEFAULT_1:
                        case IntentUtil.INTENT_ACTIONS_DEFAULT_2:
                            onBroadcastReceiver(data);
                        default:
                            break;
                    }
                } catch (Exception e) {
                    DialogUtil.showCommonAlertDialog(e.getMessage());
                }
            }

            private void onBroadcastReceiver(String barcodeData) {

                    LogUtil.file("接收到广播数据", barcodeData);
                    if (progressCount.get() > 0) {
                        ToastUtil.showWait("请等待上一个结果返回");
                        return;
                    }
                    if (datas.contains(barcodeData)) {
                        ToastUtil.showError("数据重复");
                        return;
                    }
                    //如果是出库申请开头的数据那么就是outStockApplyNos
                    if (barcodeData.indexOf("XM") == 0 || barcodeData.indexOf("01") == 0) {
                        String data0 = "";
                        if (DefaultSharedPreferencesUtil.useDeptIsProduct(PackingActivity.this) && CollectionUtils.isNotEmpty(datas)) {
                            data0 = datas.get(0);
                            //如果前两个字不一样就说明，不是同一类型（箱码和udi码）
                            if (!data0.substring(0, 2).equals(barcodeData.substring(0, 2))) {
                                ToastUtil.showError("不是同一类型的码");
                                return;
                            }
                        }
                        String useDept = DefaultSharedPreferencesUtil.getUseDept(PackingActivity.this);
                        Integer maxCount = null;
                        String maxCountStr = binding.etMaxCount.getText().toString();
                        if (!TextUtils.isEmpty(maxCountStr)) {
                            maxCount = Integer.valueOf(maxCountStr);
                            LogUtil.file("packing","最大数量:"+maxCount+"data size:"+datas.size());
                            if (datas.size() >= maxCount) {
    //                            binding.boxCodeScan.setText("");
                                DialogUtil.showCommonAlertDialog("已经达到最大数量"+maxCount+"，输入框已清空");
                                return;
                            }
                        }
                        Integer finalMaxCount = maxCount;
                        long l = System.currentTimeMillis();
                        apiService.checkPackScanBoxCode(barcodeData, data0, useDept)
                                .compose(ResponseTransformer.obtain())
                                .subscribe(ajaxResult -> {
                                    if (ajaxResult.getData(Boolean.class) && !datas.contains(barcodeData)) {
                                        ToastUtil.showLong("添加成功");
                                        String deviceNo = DefaultSharedPreferencesUtil.getDeviceNo(PackingActivity.this);
                                        LogUtil.file("装箱扫码", "扫码为：" + barcodeData);
                                        datas.add(barcodeData);
    //                                    binding.boxCodeScan.setText("");
                                        packingListViewAdapter.notifyDataSetChanged();
                                        Log.i("tag1111", "时间2:" + (System.currentTimeMillis() - l));
    //                                    binding.boxCodeScan.postDelayed(() -> {
    //                                        binding.boxCodeScan.requestFocus();
    //                                    }, 100);
                                        SoundPlayerUtil.playSuccess();
                                        if (finalMaxCount != null && datas.size() == finalMaxCount) {
                                            //达到最大震动一下
                                            VibratorUtil.vibrator();
                                        }
                                        return;
                                    }

    //                                binding.boxCodeScan.setText("");
                                    //弹出提示框
                                    DialogUtil.showCommonAlertDialog(ajaxResult.getMsg());
    //                                DialogUtil.showCommonAlertDialog(ajaxResult.getMsg(), () -> binding.boxCodeScan.requestFocus());
                                }, ErrorConsumerAdapterBuilder.builder()
                                        .before((ex) -> {
    //                                        binding.boxCodeScan.setText("");
    //                                        binding.boxCodeScan.requestFocus();
                                        })
                                        .build());
                    } else {
                        //非法数据
                        ToastUtil.showError("非法数据，请检查");
                        return;
                    }

            }
        };
        intentFilter = new IntentFilter();
        intentFilter.addAction(IntentUtil.INTENT_ACTIONS_DEFAULT_1);
        intentFilter.addAction(IntentUtil.INTENT_ACTIONS_DEFAULT_2);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册广播接收器
        registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver); // 取消广播注册
        }
        super.onPause();
    }
    */
}